package com.culture.config.component;

import java.util.List;

import javax.annotation.Resource;

import com.culture.config.dao.entity.JobInfo;
import com.culture.config.dao.entity.JobLog;
import com.culture.config.dao.mapper.AppInstanceMapper;
import com.culture.config.dao.mapper.JobLogMapper;
import com.culture.config.wrapper.JobLogWrapper;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class JobRunner {
    @Resource
	private AppInstanceMapper appInstanceMapper;
    @Resource
    private JobLogMapper jobLogMapper;
    @Autowired
	private RestTemplateEx restTemplateEx; 

    @Async
    public void asyncRun(JobInfo jobInfo){
        this.run(jobInfo);
    }

    public String run(JobInfo jobInfo){
        log.info("job schedule:{} - {}",0,jobInfo);
        String scheduleResult = execJob(jobInfo);
        this.saveJobScheduleLog(jobInfo,scheduleResult);
        this.clearJobLog(jobInfo);
        return scheduleResult;
    }

    private String execJob(JobInfo jobInfo){
        String scheduleUrl = StringUtils.join(jobInfo.getRequestUrl(), "");
        String scheduleResult = null;
        try{
            scheduleResult = this.restTemplateEx.action(jobInfo.getRequestMethod(), scheduleUrl, jobInfo.getRequestParams(), String.class);
        }catch(Exception ex){
            log.error("job schedule error:",ex);
            scheduleResult = ex.getMessage();
        }
        return scheduleResult;
    }

    private void saveJobScheduleLog(JobInfo jobInfo,String result){
        log.info("scheduleResult:{}",result);
        this.jobLogMapper.add(JobLogWrapper.wrapJobLogAdd(jobInfo, result));
    }

    private void clearJobLog(JobInfo jobInfo){
        List<JobLog> topList = this.jobLogMapper.listTopByJobId(jobInfo.getId(), 10);
        if(CollectionUtils.isEmpty(topList)){
            return;
        }
        this.jobLogMapper.clearByJobId(JobLogWrapper.wrapJobLogClear(jobInfo, topList));
    }
}
